package com.aps.apspda.dialog;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.entity.VersionEntity;
import com.aps.apspda.myview.Rotate3dAnimation;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;


/**
 * @author huangxin
 * @date 2015/11/10
 * @desc 通用dialog
 */
public class DownloadFragmentDialog extends AppCompatDialogFragment {
    private VersionEntity versionEntity;
    private Button btnRe;
    private LinearLayout llMain, llDownloadTips, llBottom;
    private RelativeLayout llDownload;
    private ProgressBar progressBar;
    private TextView tvProgress;

    private DownloadTask task;
    private boolean isFinish = false;
    private String fileFolderPath = StaticMembers.ROOT_PATH + "/" + StaticMembers.DOWN_PATH;
    private String savePath;

    public void setData(VersionEntity versionEntity) {
        this.versionEntity = versionEntity;
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (!isAdded()) {
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, tag);
            ft.commitAllowingStateLoss();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            dialog.getWindow().setLayout((int) (StaticMembers.SCREEN_WIDTH * 0.8), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (task != null) {
            task.unRegister("down_new_version");
            task.remove(!isFinish);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_download, null);
        getDialog().getWindow().setGravity(Gravity.CENTER); // 非常重要：设置对话框弹出的位置
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().getWindow().setWindowAnimations(R.style.BottomDialog); // 添加动画
        getDialog().setCanceledOnTouchOutside(false);
        getDialog().setCancelable(false);
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    ToastUtils.showFreeToast("请更新后使用", getActivity(), false, Toast.LENGTH_SHORT);
                    return true;
                }
                return false;
            }
        });
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        TextView tvVersion, tvDesc, tvCurrentVersion;
        Button btnConfirm;
        tvVersion = view.findViewById(R.id.tvVersion);
        tvCurrentVersion = view.findViewById(R.id.tvCurrentVersion);
        tvDesc = view.findViewById(R.id.tvDesc);
        tvProgress = view.findViewById(R.id.tvProgress);
        btnConfirm = view.findViewById(R.id.btnConfirm);
        btnRe = view.findViewById(R.id.btnRe);
        progressBar = view.findViewById(R.id.pbDownload);
        llMain = view.findViewById(R.id.llMain);
        llDownloadTips = view.findViewById(R.id.llDownloadTips);
        llDownload = view.findViewById(R.id.llDownload);
        llBottom = view.findViewById(R.id.llBottom);

        tvDesc.setText(versionEntity.getInfo());
        tvVersion.setText(versionEntity.getVersion());
        tvCurrentVersion.setText(String.valueOf(StaticMembers.VERSION_CODE));
        savePath = fileFolderPath + "/" + getString(R.string.app_name) + ".apk";

        btnRe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShake.check(v.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            getActivity(), false, Toast.LENGTH_SHORT);
                    return;
                }
                if (task != null) {
                    task.start();
                }
            }
        });

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AntiShake.check(view.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            getActivity(), false, Toast.LENGTH_SHORT);
                    return;
                }
                if (new File(savePath).exists()) {
                    new File(savePath).delete();
                }
                startAnAnimation();
                initDownload();
            }
        });
        super.onViewCreated(view, savedInstanceState);
    }

    private void startAnAnimation() {
        LinearLayout.LayoutParams lp2 = (LinearLayout.LayoutParams) llDownload.getLayoutParams();
        lp2.height = llDownloadTips.getHeight();
        llDownload.setLayoutParams(lp2);
        float centerX = llMain.getWidth() / 2f;
        float centerY = llMain.getHeight() / 2f;
        Rotate3dAnimation animation = new Rotate3dAnimation(0, 90, centerX, centerY,
                310.0f, true);
        // 动画持续时间500毫秒
        animation.setDuration(200);
        // 动画完成后保持完成的状态
        animation.setInterpolator(new AccelerateInterpolator());
        // 设置动画的监听器
        animation.setFillAfter(true);
        llMain.startAnimation(animation);

        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                llDownloadTips.setVisibility(View.GONE);
                llDownload.setVisibility(View.VISIBLE);
                float centerX = llMain.getWidth() / 2f;
                float centerY = llMain.getHeight() / 2f;
                // 构建3D旋转动画对象，旋转角度为270到360度，这使得ImageView将会从不可见变为可见
                Rotate3dAnimation rotation = new Rotate3dAnimation(270, 360, centerX, centerY,
                        310.0f, false);
                // 动画持续时间500毫秒
                rotation.setDuration(100);
                // 动画完成后保持完成的状态
                rotation.setFillAfter(true);
                rotation.setInterpolator(new AccelerateInterpolator());
                llMain.startAnimation(rotation);
                rotation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        Acp.getInstance(getActivity()).request(new AcpOptions.Builder()
                                        .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        .build(),
                                new AcpListener() {
                                    @Override
                                    public void onGranted() {
                                        task.start();
                                    }

                                    @Override
                                    public void onDenied(List<String> permissions) {
                                        ToastUtils.showFreeToast(permissions.toString() +
                                                getString(R.string.permission_denied), getActivity(), false, Toast.LENGTH_SHORT);
                                    }
                                });
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void initDownload() {
        File fileFolder = new File(fileFolderPath);
        if (!fileFolder.exists()) {
            fileFolder.mkdirs();
        }
        //StaticMembers.PIC_URL + versionEntity.getDownLoadURL()
        //"http://192.168.1.108:8080/file/updateAPK/aps10.apk"
        GetRequest<File> request = OkGo.get(StaticMembers.NET_URL+"/"+ versionEntity.getDownLoadURL());
        savePath  = fileFolderPath + "/" + request.getBaseUrl().substring(request.getBaseUrl().lastIndexOf("/")+1).replace(".apk","")+".apk";
        task = OkDownload.request("down_new_version", request)
                .save()
                .folder(fileFolderPath)
                //.fileName(getString(R.string.app_name) + ".apk")
                .fileName( request.getBaseUrl().substring(request.getBaseUrl().lastIndexOf("/")+1).replace(".apk","")+".apk")
                .register(new DownloadListener("down_new_version") {
                    @Override
                    public void onStart(Progress progress) {
                        llBottom.setVisibility(View.GONE);
                    }

                    @Override
                    public void onProgress(Progress progress) {
                        progressBar.setMax((int) progress.totalSize);
                        progressBar.setProgress((int) progress.currentSize);
                        double current = progress.currentSize * 1.0;
                        double total = progress.totalSize * 1.0;
                        double percent = current / total;
                        DecimalFormat df = new DecimalFormat("##%");
                        tvProgress.setText(df.format(percent));
                    }

                    @Override
                    public void onError(Progress progress) {
                        ToastUtils.showFreeToast(getString(R.string.update_fail),
                                getActivity(), false, Toast.LENGTH_SHORT);
                        AppUtils.saveErrorMessages(progress.exception, "APK下载失败");
                        llBottom.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onFinish(File file, Progress progress) {
                        isFinish = true;
                        openApk();
                        dismissAllowingStateLoss();
                        ToastUtils.showFreeToast(getString(R.string.update_complete),
                                getActivity(), true, Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onRemove(Progress progress) {

                    }
                });
    }

    private void openApk() {
        dismiss();
        //打开APK
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(Uri.fromFile(new File(savePath)), "application/vnd.android.package-archive");
        //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }
}
